package org.jiulou.web;

import java.util.Locale;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.jiulou.util.controller.ControllerUtil;
import org.jiulou.vo.LoginVo;
import org.jiulou.vo.Rtn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

@Controller
@RequestMapping(value = "/security")
public class LogInOutController{

    private static transient final Logger log = LoggerFactory.getLogger(LogInOutController.class);

	@Resource(name = "loginValidator")
	private Validator validator;
	
    @RequestMapping(value = "/alogin")
    public ModelAndView login(@ModelAttribute LoginVo vo, BindingResult result,Model model,Locale locale
    		,HttpServletRequest request, HttpServletResponse response) throws Exception {

		Rtn rtn = new Rtn();
		rtn.setCode(Rtn.SUCCESS_CODE);
		
		// 校验
		this.validator.validate(vo, result);
		if (result.hasErrors()) {
			rtn.setCode(Rtn.FAILED_CODE);
			model.addAttribute("vo",vo);
			model.addAttribute("fieldErrors",ControllerUtil.translateValidatorMsgs(result, locale));
		}else{
			// 开始登录
	        Subject subject = SecurityUtils.getSubject();
	        UsernamePasswordToken token = new UsernamePasswordToken(vo.getUsername(),vo.getPassword());

	        try {
	            subject.login(token);
	        } catch (AuthenticationException e) {
	            log.error("Error authenticating.", e);
	            result.reject("admin.login.error.password", "用户名或者密码不正确");
	            rtn.setCode(Rtn.ERROR_CODE);
	            model.addAttribute("globeErrors",ControllerUtil.translateGlobleMsgs(result, locale));
	        }
	        
	        // 登录成功
	        if (!result.hasErrors()) {
	        	
	        	SavedRequest lastRequest = WebUtils.getAndClearSavedRequest(request);
	        	String redirectUrl = "/";
	        	
	        	if(null != lastRequest){
	        		// 说明需要跳转到用户初次访问的页面
	        		redirectUrl = lastRequest.getRequestURI();
	        		if(null != lastRequest.getQueryString()){
	        			// 有参数
	        			redirectUrl = redirectUrl + "?" + lastRequest.getQueryString();
	        		}
	        	}
	        	
	        	return new ModelAndView(new RedirectView(redirectUrl));
	        }
		}
		
		// 登录失败
		model.addAttribute("rtn", rtn);
        return new ModelAndView("view/admin/login.jsp", model.asMap());
    }
    
    @RequestMapping(value = "/logout")
    public ModelAndView logout(Model model,Locale locale
    		,HttpServletRequest request, HttpServletResponse response) throws Exception {

		Rtn rtn = new Rtn();
		rtn.setCode(Rtn.SUCCESS_CODE);

		// 登出
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        
		// 跳转
		model.addAttribute("rtn", rtn);
        return new ModelAndView("view/admin/login.jsp", model.asMap());
    }
    
    @RequestMapping(value = "/unauthorized")
    public ModelAndView unauthorized(Model model,Locale locale
    		,HttpServletRequest request, HttpServletResponse response) throws Exception {
        
        return new ModelAndView("admin/unauthorized.ftl");
    }
    
}